<template>
  <div class="ele-body ele-body-layout">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>信息流复制报告</span>
      </div>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="url"
        :highlight-current-row="true"
        :max-height="defaultHeight"
        :parse-data="parseData"
        :selection.sync="selection"
        :summary-method="summaries"
        :where="where"
        show-summary
      >
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <!-- 搜索表单 -->
          <el-form
            :model="where"
            class="ele-form-search"
            label-width="75px"
            @keyup.enter.native="reload"
            @submit.native.prevent
          >
            <div class="app-container">
              <div class="filter-container">
                <el-select
                  v-model="where.bazaarId"
                  clearable
                  placeholder="推广市场"
                  style="margin-right: 6px"
                  @change="changebazaarId"
                >
                  <template v-for="item in bazaarList">
                    <el-option
                      v-if="item.status === 1"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </template>
                </el-select>

                <el-select
                  v-model="where.userid"
                  clearable
                  placeholder="推广账户"
                  style="margin-right: 6px"
                  @change="changeuserid"
                >
                  <template v-for="item in expandList">
                    <el-option
                      v-if="item.status === 1"
                      :key="item.userid"
                      :label="item.username"
                      :value="item.userid"
                    />
                  </template>
                </el-select>

                <el-select
                  v-model="where.campaignId"
                  clearable
                  collapse-tags
                  multiple
                  placeholder="推广计划"
                  style="margin-right: 6px"
                  @change="reload"
                >
                  <template v-for="item in campaignList">
                    <el-option
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </template>
                </el-select>

                <el-date-picker
                  v-model="daterange"
                  :clearable="false"
                  :picker-options="pickerOptions"
                  end-placeholder="数据结束日期"
                  range-separator="-"
                  start-placeholder="数据开始日期"
                  style="width: 230px; margin-right: 6px"
                  type="datetimerange"
                  unlink-panels
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="onDateRangeChoose"
                />

                <el-button
                  icon="el-icon-search"
                  style="margin-right: 6px"
                  type="primary"
                  @click="reload"
                  >搜索
                </el-button>

                <el-button
                  icon="el-icon-refresh"
                  style="margin-left: 2px"
                  @click="reset"
                  >重置
                </el-button>
              </div>
            </div>
          </el-form>
        </template>

        <!-- 推广市场列 -->
        <template slot="bazaarId" slot-scope="{ row }">
          <template v-for="item in bazaarList">
            <span v-if="row.bazaarId === item.id" :key="item.id">
              {{ item.name }}
            </span>
          </template>
        </template>

        <!-- 推广账户列 -->
        <template slot="userId" slot-scope="{ row }">
          <template v-for="item in tempexpandList">
            <span v-if="row.userId === item.userid" :key="item.id">
              {{ item.username }}
            </span>
          </template>
        </template>

        <!-- 现金消费列 -->
        <template slot="cash" slot-scope="{ row }">
          <el-popover
            placement="top-start"
            popper-class="cash-remove-popover"
            title="消费明细"
            trigger="hover"
            width="200"
            @hide="popoverHide"
          >
            现金消费{{ row.cash }}元, 账户返点: {{ row.rebate }}
            <span slot="reference" style="cursor: pointer">{{ row.cash }}</span>
          </el-popover>
        </template>

        <!-- 点击率列 -->
        <template slot="ctr" slot-scope="{ row }">
          <span>{{ row.ctr }}% </span>
        </template>

        <!--推广单元筛选-->
        <template slot="descHeader" slot-scope="{ column }">
          <span>{{ column.label }}</span>
          <span
            style="position: absolute; right: 8px; font-size: 14px"
            @click.stop.prevent=""
          >
            <el-popover
              v-model="descHeaderVisible"
              placement="bottom"
              trigger="click"
            >
              <i slot="reference" class="el-icon-_filter"></i>
              <div style="margin-bottom: 10px">
                <el-select
                  v-model="where.filtrateType"
                  placeholder="请选择"
                  size="mini"
                >
                  <el-option
                    v-for="item in filtrateArray"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </div>
              <div>
                <el-input
                  v-model="where.filtrateValue"
                  placeholder="请输入欲筛选内容"
                  size="mini"
                ></el-input>
              </div>
              <div style="margin-top: 10px">
                <el-button size="mini" type="primary">确定</el-button>
                <el-button size="mini" @click="descHeaderVisible = false"
                  >取消</el-button
                >
              </div>
            </el-popover>
          </span>
        </template>
      </ele-pro-table>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "feedCopy",
  data() {
    return {
      //是否关闭筛选
      descHeaderVisible: false,
      //筛选数组
      filtrateArray: [
        { value: "like", label: "包含" },
        { value: "equal", label: "等于" },
        { value: "greater", label: "大于" },
        { value: "greaterequal", label: "大于等于" },
        { value: "less", label: "小于" },
        { value: "lessequal", label: "小于等于" },
        { value: "nolike", label: "不包含" },
        { value: "unequal", label: "不等于" },
        { value: "start", label: "开头字符" },
        { value: "end", label: "结尾字符" },
      ],
      //数据合计
      total: Object,
      // 账户列表
      expandList: [],
      // 账户列表
      tempexpandList: [],
      //市场列表
      bazaarList: [],
      //计划列表
      campaignList: [],
      // 表格高度
      defaultHeight: 0,
      // 筛选日期范围
      daterange: this.getDaterange(),
      // 日期时间选择器快捷项
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime());
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime() + 24 * 60 * 60 * 1000);
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 24 * 60 * 60 * 1000);
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 7 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 15 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 30 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 90 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近半年",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 180 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一年",
            onClick(picker) {
              let start = new Date();
              start.setTime(start.getTime() - 365 * (24 * 60 * 60 * 1000));
              start =
                start.getFullYear() +
                "-" +
                (start.getMonth() + 1) +
                "-" +
                start.getDate() +
                " 00:00:00";
              let end = new Date();
              end.setTime(end.getTime());
              end =
                end.getFullYear() +
                "-" +
                (end.getMonth() + 1) +
                "-" +
                end.getDate() +
                " 00:00:00";
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 表格数据接口
      url: "/FeedCopy/read",
      // 表格列配置
      columns: [
        {
          columnKey: "index",
          type: "index",
          width: 80,
          label: "序号",
          align: "center",
          showOverflowTooltip: true,
        },
        {
          prop: "userId",
          slot: "userId",
          label: "推广账户",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "bazaarId",
          label: "推广市场",
          slot: "bazaarId",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "campaignName",
          label: "推广计划",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "adgroupName",
          label: "推广单元",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "impression",
          label: "展现",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "clicks",
          label: "点击",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "cost",
          label: "消费",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "cash",
          slot: "cash",
          label: "现金消费",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "cpc",
          label: "CPC",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "ctr",
          slot: "ctr",
          label: "点击率",
          sortable: "custom",
          resizable: false,
        },
        {
          width: 100,
          prop: "copynumber",
          label: "目标转化量",
          sortable: true,
          showOverflowTooltip: true,
        },
        {
          width: 110,
          prop: "copycost",
          label: "目标转化成本",
          sortable: true,
          resizable: false,
        },
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
    };
  },
  created() {
    window.addEventListener("resize", this.setHeight);
    this.setHeight();
  },

  methods: {
    changebazaarId(id) {
      this.expandList = [];
      this.campaignList = [];
      this.where.userid = "";
      this.where.campaignId = "";
      for (let i = 0; i < this.tempexpandList.length; i++) {
        if (this.tempexpandList[i].bazaarId === id) {
          this.expandList.push(this.tempexpandList[i]);
        }
      }
      this.reload();
    },

    changeuserid(obj) {
      this.campaignList = [];
      this.where.campaignId = "";
      this.$http
        .post("/FeedCopy/getCampaign", { userid: obj })
        .then((res) => {
          if (res.data.code === 0) {
            this.campaignList = res.data.campaign;
            this.reload();
          }
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },

    summaries(param) {
      const { columns, data } = param,
        createDiv = function (t1, t2) {
          return (() => {
            return (
              <el-col>
                <el-col class="el-table_target_sum">{t1}</el-col>
                <el-col class="el-table_target_bar"></el-col>
                <el-col class="el-table_target_total">{t2}</el-col>
              </el-col>
            );
          })();
        };
      let result = [],
        sum1 = 0,
        sum2 = 0,
        sum3 = 0,
        sum4 = 0,
        sum5 = 0,
        sum6 = 0,
        sum7 = 0,
        sum8 = 0,
        sum9 = 0,
        sum10 = 0;
      columns.forEach((column, index) => {
        switch (column.property) {
          case "adgroupName":
            result[index] = createDiv("小计", "合计");
            break;

          case "impression":
            sum1 = this.getcolumn(data, column.property, true);
            result[index] = createDiv(sum1, this.total.impression);
            break;

          case "clicks":
            sum2 = this.getcolumn(data, column.property, true);
            result[index] = createDiv(sum2, this.total.clicks);
            break;

          case "cost":
            sum3 = this.getcolumn(data, column.property, false);
            result[index] = createDiv(sum3, this.total.cost);
            break;

          case "cash":
            sum4 = this.getcolumn(data, column.property, false);
            result[index] = createDiv(sum4, this.total.cash);
            break;

          case "cpc":
            sum5 = this.getcolumn(data, column.property, false);
            result[index] = createDiv(sum5, this.total.cpc);
            break;

          case "ctr":
            sum6 = (sum2 / sum1) * 100;
            if (isNaN(sum6)) {
              sum6 = 0;
            }
            sum9 = (this.total.clicks / this.total.impression) * 100;
            if (isNaN(sum9)) {
              sum9 = 0;
            }
            result[index] = createDiv(
              sum6.toFixed(2) + "%",
              sum9.toFixed(2) + "%"
            );
            break;

          case "copynumber":
            sum7 = this.getcolumn(data, column.property, true);
            result[index] = createDiv(sum7, this.total.copynumber);
            break;

          case "copycost":
            sum8 = this.getcolumn(data, column.property, false);
            if (sum7 == 0) {
              sum10 = sum8;
            } else {
              sum10 = sum3 / sum7;
              if (sum10 > 0) {
                sum10 = sum10.toFixed(2);
              }
              if (isNaN(sum10)) {
                sum10 = sum8;
              }
            }
            result[index] = createDiv(sum10, this.total.copycost);
            break;
        }
      });
      return result;
    },

    getcolumn(data, column, integer) {
      if (data.length === 0) {
        return 0;
      }
      let sums = 0;
      const values = data.map((item) => Number(item[column]));
      if (!values.every((value) => isNaN(value))) {
        sums = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      }
      if (integer) {
        return sums;
      }
      return sums.toFixed(2);
    },

    popoverHide() {
      const popover = document.getElementsByClassName("cash-remove-popover");
      for (let i = 0; i < popover.length; i++) {
        popover[i].remove();
      }
    },

    /*默认时间*/
    getDaterange() {
      let start = new Date();
      start.setTime(start.getTime());
      start =
        start.getFullYear() +
        "-" +
        (start.getMonth() + 1) +
        "-" +
        start.getDate() +
        " 00:00:00";
      let end = new Date();
      end.setTime(end.getTime() + 24 * 60 * 60 * 1000);
      end =
        end.getFullYear() +
        "-" +
        (end.getMonth() + 1) +
        "-" +
        end.getDate() +
        " 00:00:00";
      return [start, end];
    },

    /* 日期选择改变回调 */
    onDateRangeChoose() {
      if (this.daterange && this.daterange.length === 2) {
        this.where.createTimeStart = this.daterange[0];
        this.where.createTimeEnd = this.daterange[1];
      } else {
        this.where.createTimeStart = null;
        this.where.createTimeEnd = null;
      }
    },

    /*设置表格高度*/
    setHeight() {
      this.defaultHeight = window.innerHeight - 360;
    },

    /*表格数据加载*/
    parseData(res) {
      if (res.code === 0) {
        this.total = res.total;
        this.bazaarList = res.bazaar;
        this.tempexpandList = res.expand;
      }
      return {
        code: res.code,
        data: res.data,
        count: res.count,
        msg: res.msg,
      };
    },

    /* 刷新表格 */
    reload(isPage) {
      let obj = { where: this.where };
      if (!isPage) {
        obj.page = 1;
      }
      this.$refs.table.reload(obj);
    },

    /* 重置搜索 */
    reset() {
      for (let key in this.where) {
        this.where[key] = null;
      }
      let daterange = this.getDaterange();
      if (daterange.length === 2) {
        this.where.createTimeStart = daterange[0];
        this.where.createTimeEnd = daterange[1];
      }
      this.daterange = daterange;
      this.reload();
    },

    /*时间格式化*/
    formatTime(value) {
      const stamp = new Date().getTime() - new Date(value).getTime();
      if (stamp >= 1000 * 60 * 60 * 24) {
        return ((stamp / 1000 / 60 / 60 / 24) | 0) + "天前";
      } else if (stamp >= 1000 * 60 * 60) {
        return ((stamp / 1000 / 60 / 60) | 0) + "小时前";
      } else if (stamp >= 60000) {
        //1分钟以内为：刚刚
        return ((stamp / 1000 / 60) | 0) + "分钟前";
      }
      return "刚刚";
    },
  },
};
</script>

<style scoped>
</style>
